import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/edit_delete_pop_menu_widget.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_bind_new_terminal_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_simple_store_list_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_and_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/vg_widgets/custom_empty_widget.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/general_animation_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'event/refresh_smart_home_index_event.dart';

/// 门店设备页面
class SmartHomeStoreAndTerminalPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeStoreAndTerminalPage";
  //标题
  final String shid;

  const SmartHomeStoreAndTerminalPage(
      {Key key,this.shid}) : super(key:key);

  @override
  _SmartHomeStoreAndTerminalPageState createState() => _SmartHomeStoreAndTerminalPageState();

  static Future<Map> navigatorPush(BuildContext context, String shid){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeStoreAndTerminalPage(
          shid: shid,
        ),
        routeName: SmartHomeStoreAndTerminalPage.ROUTER
    );
  }
}

class _SmartHomeStoreAndTerminalPageState
    extends BaseState<SmartHomeStoreAndTerminalPage> {
  TextEditingController _titleController;
  SmartHomeViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  BindingTerminalViewModel _bindTerminalViewModel;
  String _searchStr;

  List<SmartHomeStoreAndTerminalListData> data;
  String _latestGps;
  VgLocation _locationPlugin;

  StreamSubscription _updateStreamSubscription;

  @override
  void initState() {
    super.initState();
    data = new List();
    _viewModel = SmartHomeViewModel(this);
    _detailViewModel = SmartHomeStoreDetailViewModel(this);
    _bindTerminalViewModel = BindingTerminalViewModel(this);
    Future<String> latlng = VgLocationUtils.getCacheLatLngString();
    latlng.then((value){
      print("缓存gps:" + value);
      _latestGps = value;
      _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr);
    });
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((data) {
      if(data.containsKey("latitude") && data.containsKey("longitude")){
        LatLngBean latLngBean = LatLngBean.fromMap(data);
        String gps = latLngBean.latitude.toString() + "," + latLngBean.longitude.toString();
        print("获取到了最新gps:" + gps);
        _latestGps = gps;
        _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr);
      }
    });
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is LocationChangedEvent) {
        print("收到gps更新的:" + event?.gps);
        if(StringUtils.isNotEmpty(event?.gps??"")){
          if(event?.gps == _latestGps){
            print("更新的gps与当前一致，不执行刷新");
            return;
          }
          _latestGps = event?.gps;
          _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr);
        }
      }
    });

    _updateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeIndexEvent>()?.listen((event) {
          _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr);
        });
  }

  @override
  void dispose() {
    _titleController?.clear();
    _titleController?.dispose();
    _updateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return CommonPackUpKeyboardWidget(
      child: Column(
        children: [
          _toTopBarWidget(),
          _toSearchWidget(),
          Expanded(
            child: _toPlaceHolderWidget(),
          ),
        ],
      ),
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "门店设备",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toBindNewTerminalWidget(),
    );
  }

  Widget _toBindNewTerminalWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SmartHomeBindNewTerminalPage.navigatorPush(context, _latestGps, widget?.shid??"");
      },
      child: Container(
        width: 84,
        height: 24,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          borderRadius: BorderRadius.circular(12),
        ),
        alignment: Alignment.center,
        child: Text(
          "绑定新设备",
          style: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w500
          ),
        ),
      ),
    );
  }

  ///搜索
  Widget _toSearchWidget(){
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          SizedBox(height: 10),
          CommonSearchBarWidget(
            hintText: "搜索门店",
            onSubmitted: (String searchStr) {
              _searchStr = searchStr;
              _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr);
            },
            bgColor: Color(0xFFF1F4F8),
            textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }


  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            emptyCustomWidget: CustomEmptyWidget(imgAsset: "images/icon_empty_white.png", msg: "暂无内容", textColor: VgColors.INPUT_BG_COLOR,),
            errorCustomWidget: CustomEmptyWidget(imgAsset: "images/icon_empty_white.png", msg: "网络断线 重新获取", textColor: VgColors.INPUT_BG_COLOR,),
            errorOnClick: () => _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr),
            loadingOnClick: () => _viewModel.getStoreAndTerminalList(widget?.shid, _latestGps, _searchStr),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.smartHomeStoreAndTerminalListValueNotifier,
        builder: (BuildContext context, List<SmartHomeStoreAndTerminalListData> terminalList, Widget child){
          if(terminalList != null){
            data.clear();
            data.addAll(terminalList);
          }
          return _toListWidget();
        }
    );
  }

  ///图片展示栏
  Widget _toListWidget(){
    return ListView.separated(
      padding: EdgeInsets.only(top: 0, bottom: 145),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index,);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox(height: 10,);
      },
      itemCount: data?.length??0,
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index){
    return Column(
      children: [
        _toStoreInfoWidget(data?.elementAt(index)),
        _toSplitWidget(data?.elementAt(index)),
        _toNoTerminalListWidget(data?.elementAt(index)),
        _toTerminalListWidget(data?.elementAt(index)),
      ],
    );
  }

  void toSmartHomeDetailPage(SmartHomeStoreAndTerminalListData data){
    // SmartHomeOneDetailsPage.navigatorPush(context, data?.shid, data?.brand, data?.name, data?.logo);
    SmartHomeStoreDetailsPage.navigatorPush(context, data?.shid, "", data?.name, data?.logo);
  }

  ///顶部品牌门店名
  Widget _toStoreInfoWidget(SmartHomeStoreAndTerminalListData data){
    String asset = "images/icon_arrow_up.png";
    if(!(data?.expandTerList??true)){
      asset = "images/icon_arrow_down.png";
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if((data?.terList?.length??0)>0){
          data?.expandTerList =  !(data?.expandTerList??true);
          setState(() { });
        }else{
          // toSmartHomeDetailPage(data);
        }
      },
      child: Container(
        height: 45,
        color: Colors.white,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Expanded(
              child: Text(
                data.getTitle(),
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            SizedBox(width: 15,),
            Visibility(
              visible: (data?.terList?.length??0)>0,
              child: Image.asset(
                asset,
                width: 11,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///分隔线
  Widget _toSplitWidget(SmartHomeStoreAndTerminalListData data){
    if((data?.terList?.length??0)>0){
      return Visibility(
        visible: (data?.terList?.length??0)>0,
        child: Container(
          height: 1,
          color: Colors.white,
          child: Container(
            height: 1,
            color: Color(0xFFF6F7F9),
          ),
        ),
      );
    }
    return SizedBox();
  }

  ///无设备状态布局
  Widget _toNoTerminalListWidget(SmartHomeStoreAndTerminalListData data){
    if((data?.terList?.length??0) < 1){
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          // toSmartHomeDetailPage(data);
        },
        child: Container(
          color: Colors.white,
          alignment: Alignment.center,
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Container(
                  height: 120,
                  width: 111,
                  child: Image.asset("images/icon_un_bind_light.png")),
              SizedBox(
                height: 11,
              ),
              Text(
                "该门店下暂无终端显示屏",
                style: TextStyle(color: Color(0XFF8B93A5), fontSize: 14),
              ),
              SizedBox(
                height: 30,
              ),
            ],
          ),
        ),
      );
    }
    return SizedBox();
  }

  ///终端列表
  Widget _toTerminalListWidget(SmartHomeStoreAndTerminalListData data){
    return Visibility(
      visible: data?.expandTerList??true,
      child: ListView.separated(
        padding: EdgeInsets.only(top: 0, bottom: 0),
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return Container(
            height: 87,
            padding: const EdgeInsets.only(left: 15),
            alignment: Alignment.centerLeft,
            color: Colors.white,
            child:  _toContentWidget(data?.shid, data?.terList?.elementAt(index), index),
          );
        },
        separatorBuilder: (BuildContext context, int index){
          return SizedBox();
        },
        itemCount: data?.terList?.length??0,
      ),
    );
  }

  Widget _toContentWidget(String shid, TerInfoBean itemBean, int index) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn);
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Spacer(),
              Visibility(
                child: Container(
                  alignment: Alignment.centerRight,
                  width: 60,
                  margin: EdgeInsets.only(right: 15),
                  child: Text(
                    (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())?"已关机":"开机状态",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())
                          ?Color(0xFF8B93A5)
                          :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Container(
            width: 236,
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: Color(0xFF8B93A5),
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 4,
          ),
          Row(
            children: [
              Text(
                "管理员：${itemBean?.manager ?? "-"}${itemBean?.getLoginStr()?? ""}",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Color(0xFF8B93A5),
                  fontSize: 12,
                ),
              ),
              Spacer(),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTapUp: (details){
                  showAnimationDialog(
                      context: context,
                      transitionType: TransitionType.fade,
                      barrierColor: Color(0x00000001),
                      transitionDuration: Duration(milliseconds: 100),
                      builder: (context) {
                        return EditDeletePopMenuWidget(
                          items: ["更换所属门店", "删除设备"],
                          details: details,
                          onClickItem: (content) async{
                            if (content == "更换所属门店") {
                              RouterUtils.pop(context);
                              SmartHomeSimpleStoreListPage.navigatorPush(context, shid, itemBean?.hsn, itemBean?.rasid);
                            }else if (content == "删除设备") {
                              bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                                title: "提示",
                                content: "确定解绑并删除该终端显示屏？",
                                cancelText: "取消",
                                confirmText: "确定",
                                confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                                cancelBgColor: Color(0xFFF6F7F9),
                                titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                                contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                                widgetBgColor: Colors.white,
                              );
                              if (result ?? false) {
                                _bindTerminalViewModel.unBindTerminal(context, itemBean?.hsn, callback: (){
                                  RouterUtils.pop(context);
                                });
                                // _detailViewModel.setSmartHomeToTerminal(context, "00", widget?.shid, "", itemBean?.hsn, () {
                                //   _viewModel?.unBindTerminal(context, widget?.hsn, router: widget?.router);
                                // });
                              }

                            }
                          },
                        );
                      }
                  );
                },
                child: Container(
                  width: 53,
                  height: 20,
                  padding: EdgeInsets.only(right: 15),
                  alignment: Alignment.centerRight,
                  child: Image.asset(
                    "images/icon_edit_floor_company_info.png",
                    width: 3,
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

}
